package fm.dongman.animefm.view.fragment

import android.content.Context
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ChatContract
import fm.dongman.animefm.contractlib.contract.MyContract
import fm.dongman.animefm.view.adapter.ChatMessageAdapter
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.ChatDialog
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.MsgModel
import fm.dongman.presenterlib.presenter.ChatPresenter
import kotlinx.android.synthetic.main.fragment_chat.*
import org.jetbrains.anko.onClick
import java.util.ArrayList


/**
 * 私信会话页面
 * Created by shize on 2017/11/5.
 */
class ChatFragment : BaseFragment(), ChatContract.IChatView {
    private lateinit var mPresenter: ChatContract.IChatPresenter // 全局数据控制器
    private var mChatId: String? = null // 私信 ID
    private lateinit var mOtherId: String // 别人的id
    private lateinit var mMyId: String //自己的ID
    lateinit var mUserName: String //用户名


    private val mChadList: ArrayList<IModel.IMsgModel> = ArrayList() //消息集合
    private lateinit var mChadMessageAdapter: ChatMessageAdapter         //消息适配器

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        ChatPresenter(this, Injection.provideChatEditRepository())
        val view = inflater!!.inflate(R.layout.fragment_chat, container, false)
        return view
    }

    override fun initData() {
        mOtherId = arguments.getString(FLAG_ID)
        mUserName = arguments.getString(FLAG_CHAT_NAME)
        mMyId = MyContract.USER_ID!!
        sendEmptyMsg()
        mTvChatTrName.text = mUserName

    }

    override fun bindData() {
        mChadMessageAdapter = ChatMessageAdapter(mChadList, activity, mMyId)  //初始化
        mMsgRecyclerView.adapter = mChadMessageAdapter
        mMsgRecyclerView.layoutManager = LinearLayoutManager(activity)
        bindOclick() //绑定事件

    }

    private fun bindOclick() {
        mTvContTextText.onClick {
            ChatDialog.Builder(activity).setText(mTvContTextText.text.toString()).setDialogListener(object : ChatDialog.Builder.DialogListener {
                override fun onTextChanged(text: String?) {
                    mTvContTextText.text = text
                }

                override fun onSend(text: String?) {
                    sendMessage()
                }
            }).Build().show()
        }

        //发送消息事件
        mBtnRegGetCode.onClick {
            sendMessage()
        }
        //返回按钮
        mUserInfoReturn.onClick {
            activity.finish()
        }
    }

    private fun sendMessage() {
        if ("" != mTvContTextText.text) {
            val model = MsgModel()
            model.id = mMyId         //自己Id
            model.userId = mOtherId     //别人Id

            model.content = mTvContTextText.text.toString()
            mPresenter.sendChat(model)
            mTvContTextText.text = ""
        } else {
            ToastHelper.getInstance(activity).showError("消息不能为空")
        }
    }

    /**
     * 发空消息
     */
    private fun sendEmptyMsg() {
        val model = MsgModel()
        model.id = mMyId         //自己Id
        model.userId = mOtherId     //别人Id

        model.content = ""
        mPresenter.sendChat(model)
    }

    override fun setPresenter(presenter: ChatContract.IChatPresenter) {
        mPresenter = presenter
    }

    override fun showNoNetwork() {
        //  ToastHelper.getInstance(activity).showWarn("没有网络，请联网再试！")
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError("刷新失败")
    }

    override fun showHistoryChat(chats: List<IModel.IMsgModel>) {
        mChadList.clear()
        chats.filter { (it as MsgModel).content != "" }.forEach { mChadList.add(it) }
        mChadMessageAdapter.notifyDataSetChanged()
        if (mChadList.size > 1)
            mMsgRecyclerView.smoothScrollToPosition(chats.size - 1)
    }

    override fun showSendChatSucceed(chat: IModel.IMsgModel) {
        // 第一次发送消息加载chatId
        if (mChatId == null) {
            mChatId = (chat as MsgModel).chartId
            mPresenter.setChatId(mChatId!!)
        }
        mChadList.add(chat)
        mChadMessageAdapter.notifyDataSetChanged()
        mMsgRecyclerView.smoothScrollToPosition(mChadList.size - 1)

    }

    override fun showSendChatFailed() {
        ToastHelper.getInstance(activity).showError("发送消息失败！")
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    companion object {
        private val FLAG_ID = "fm.dongman.animefm.chatFragment.flagId" // 别人 userId key
        private val FLAG_CHAT_ID = "fm.dongman.animefm.chatFragment.chatId" // 私信 id
        private val FLAG_CHAT_NAME = "fm.dongman.animefm.chatFragment.username" // 用户name
        /**
         * 获取实例
         */
        fun getInstance(flagId: String, chatName: String): ChatFragment {
            val bundle = Bundle()
            bundle.putString(FLAG_ID, flagId)
            bundle.putString(FLAG_CHAT_NAME, chatName)
            val fragment = ChatFragment()
            fragment.arguments = bundle
            return fragment
        }
    }
}